#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#Google App Engine's modules
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util, template
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

#Group-written modules
from functions import *
from VidHandler import *
from ResultsHandler import *
from FavoritesHandler import *
from DelFavoritesHandler import *

#Parsing modules
from xml.dom.minidom import parseString
import cgi
import os
import gdata.youtube    
import gdata.youtube.service
import urlparse, xmlrpclib, subprocess
import sys
      
class MainHandler(webapp.RequestHandler):
  @login_required
  def get(self):
    user = users.get_current_user()
    logout_url = users.create_logout_url('/')
    #most popular videos
    c_url = []
    c_title = []

    uri = "http://gdata.youtube.com/feeds/api/standardfeeds/most_popular"
    GetAndPrintVideoFeed(uri,c_url,c_title)
    
    #keeping track of favorites
    user_favs = db.GqlQuery("SELECT * FROM Fav WHERE favOwn = :1",users.get_current_user())

    fav_title = []
    fav_url = []
    fav_code = []
        
    for favs in user_favs:
        fav_title.append(favs.title)
        fav_url.append(favs.vid_idx)
        fav_code.append(favs.code)
    
    template_values = { 
      'user': user,
      'logout': logout_url,
      'c': zip(c_url[:9], c_title[:9]),
      'favs': zip(fav_url[:10], fav_title[:10],fav_code[:10]),
    }
	
    path = os.path.join('templates', 'index.html') 
    self.response.out.write(template.render(path, template_values))

def main():
  application = webapp.WSGIApplication([('/', MainHandler), ('/VidPage', VidPageHandler), ('/results', ResultsHandler) , ('/favorites', FavoritesHandler), ('/delfavorites',DelFavoritesHandler)],
                                       debug=True)
  
  util.run_wsgi_app(application)


if __name__ == '__main__':
  main()
